import * as THREE from 'three'
import { onMounted, onUnmounted, type Ref } from 'vue'

export default function useInitThree(
  container: Ref,
  width: number,
  height: number,
  antialias: boolean = true
) {
  // 创建场景
  const scene = new THREE.Scene()
  // 创建相机
  const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000)

  // 创建渲染器
  const renderer = new THREE.WebGLRenderer({ antialias })
  renderer.setSize(width, height)

  // 监听窗口大小变化
  const handleResize = () => {
    camera.aspect = width / height
    camera.updateProjectionMatrix()
    renderer.setSize(width, height)
  }
  // 挂载时开始动画
  onMounted(() => {
    container.value.appendChild(renderer.domElement)
    window.addEventListener('resize', handleResize)
  })

  // 卸载时清理资源
  onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
    renderer.dispose()
    if (container.value) {
      container.value.removeChild(renderer.domElement)
    }
  })

  return { renderer, scene, camera }
}
